<script setup lang="ts">
import { ref, defineProps, onMounted, computed, nextTick, watch } from 'vue'
import { cloneDeep } from 'lodash'
import { TitleItem } from '@/api/common'
import { getRygnpz } from '@/utils/table-header'
import { useMainStore } from '@/store/main'
import { ElMessage } from 'element-plus'
import Sortable from 'sortablejs'
const store = useMainStore()
const props = defineProps({
  types: String,
  tableHeade: Array<TitleItem>,
  gnbm: String,
})

// 获取ref
const leftTable = ref()
const rightTable = ref()

const leftList = ref<TitleItem[]>([])

const rightList = ref<TitleItem[]>([])

onMounted(() => {
  getHeaderData()
})
// 表格拖动
const rowDropInit = () => {
  const tbody = rightTable.value?.$refs.tableBody as any
  Sortable.create(tbody.tBodies[0], {
    handle: '.allowDrag',
    animation: 150,
    swapThreshold: 0.65,
    onEnd({ newIndex, oldIndex }: { newIndex: number; oldIndex: number }) {
      const tableData = JSON.parse(JSON.stringify(rightList.value))
      rightList.value = []
      nextTick(() => {
        // 删除原位置元素，并新增到新位置
        const currRow = tableData.splice(oldIndex, 1)[0]
        tableData.splice(newIndex, 0, currRow)
        rightList.value = tableData
      })
    },
  })
}

// 监听功能数组变化，修改数组发出事件
watch(
  () => rightList.value,
  () => {
    if (rightList.value && rightList.value.length > 0) {
      // 表格拖动初始化
      nextTick(() => {
        rowDropInit()
      })
    }
  },
  {
    deep: true,
    immediate: true,
  },
)
watch(
  () => props.gnbm,
  () => {
    getHeaderData()
  },
)
const transferRight = () => {
  const selection = leftTable.value.getSelectionRows()
  leftList.value = leftList.value.filter((item) => !selection.includes(item))
  rightList.value = rightList.value.concat(selection)
}

const transferLeft = () => {
  const selection = rightTable.value.getSelectionRows()
  rightList.value = rightList.value.filter((item) => !selection.includes(item))
  leftList.value = leftList.value.concat(selection)
}

// 选项选中发生改变时
const handleSelectionChange = (type: any) => {
  // const table = type === 'left' ? leftTable.value : rightTable.value
  // const selection = table.getSelectionRows()
}

/*
 * 根据功能查询所有表头数据
 */
const getHeaderData = async () => {
  const param = {
    dwbm: store.$state.userInfo.dwbm,
    rybm: store.$state.userInfo.ryid,
    gnbm: props.gnbm || '',
  }
  const arr = (await getRygnpz(param)) as unknown as TitleItem[]
  if (!arr) {
    defaultHeader()
  } else if (typeof arr === 'object') {
    rightList.value = arr
    getLeftTable()
  } else {
    const value = arr as any
    ElMessage.warning(value.message)
  }
}

/**
 * 默认设置
 */
const defaultHeader = () => {
  rightList.value = cloneDeep(props.tableHeade || [])
  getLeftTable()
}

/**
 * 获取左侧过滤数据
 */
const getLeftTable = () => {
  const allData = cloneDeep(props.tableHeade || [])
  leftList.value = allData.filter((el) => {
    return !rightList.value.find((kl) => kl.prop === el.prop)
  })
}

/**
 * 多选禁用
 */
const selectable = (row: any) => {
  return row.prop !== 'ajmc' && row.prop !== 'ajBmWj'
}

/**
 * 表格过滤
 */
// 左边关键词搜索
const leftSearchValue = ref('')
// 右边关键词搜索
const rightSearchValue = ref('')
const filterLeftList = computed(() =>
  leftList.value.filter((data) => {
    return data.label.includes(leftSearchValue.value)
  }),
)
const filterRightList = computed(() =>
  rightList.value.filter((data) => {
    return data.label.includes(rightSearchValue.value)
  }),
)

defineExpose({ defaultHeader, rightList, rightTable, leftTable })
</script>
<template>
  <div class="table-transfer">
    <div class="table-transfer-left">
      <div class="left-top">
        <el-input
          placeholder="请输入查询关键字"
          v-model="leftSearchValue"
          maxlength="100"
          clearable
        />
      </div>
      <el-table
        ref="leftTable"
        :data="filterLeftList"
        height="100%"
        style="width: 100%"
        @selection-change="handleSelectionChange('left')"
      >
        <el-table-column type="selection"></el-table-column>
        <el-table-column prop="label" label="表头名称" align="center"></el-table-column>
      </el-table>
    </div>
    <div class="table-transfer-buttons">
      <el-button type="primary" icon="arrow-right" @click="transferRight"></el-button>
      <el-button
        style="margin-top: 10px"
        type="primary"
        icon="arrow-left"
        @click="transferLeft"
      ></el-button>
    </div>
    <div class="table-transfer-right">
      <div class="right-top">
        <el-input
          style="width: 50%"
          placeholder="请输入查询关键字"
          v-model="rightSearchValue"
          maxlength="100"
          clearable
        />
      </div>
      <el-table
        ref="rightTable"
        :data="filterRightList"
        style="width: 100%"
        height="100%"
        @selection-change="handleSelectionChange('right')"
      >
        <el-table-column type="selection" :selectable="selectable"></el-table-column>
        <el-table-column prop="label" label="表头名称" align="center">
          <template #default="{ row }">
            <div style="cursor: all-scroll" class="allowDrag">
              {{ row.label }}
            </div>
          </template>
        </el-table-column>
        <template v-if="props.types === 'list'">
          <el-table-column prop="width" label="列宽度" style="text-align: center" align="center">
            <template #default="scope">
              <el-input-number
                type="number"
                v-model="scope.row.width"
                placeholder="请输入内容"
              ></el-input-number>
            </template>
          </el-table-column>
          <el-table-column prop="dqfs" label="对齐方式" align="center">
            <template #default="scope">
              <el-select v-model="scope.row.dqfs" placeholder="请选择对齐方式">
                <el-option label="居左" value="left" />
                <el-option label="居中" value="center" />
                <el-option label="居右" value="right" />
              </el-select>
            </template>
          </el-table-column>
        </template>
      </el-table>
    </div>
  </div>
</template>
<style lang="scss" scoped>
.table-transfer {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  height: 600px;
}
.table-transfer-left {
  width: 30%;
  height: 100%;
  .left-top {
    margin-bottom: 10px;
  }
}
.table-transfer-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  width: 10%;
  height: 100%;
}

.table-transfer-right {
  flex: 1;
  height: 100%;
  max-width: calc(70% - 90px);

  .right-top {
    margin-bottom: 10px;
  }
}
:deep(.el-button + .el-button) {
  margin-left: 0;
}
</style>
